package com.qiniuyun.backai.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.qiniuyun.backai.common.ErrorCode;
import com.qiniuyun.backai.exception.BusinessException;
import com.qiniuyun.backai.model.pojo.AudioRequest;
import com.qiniuyun.backai.model.pojo.AudioResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;

@Slf4j
@Component
public class AudioUtil {
    @Value("${audio.key}")
    private String key;
    @Value("${audio.url}")
    private String url;

    public void getAudio(String prompt,String fileurl) throws IOException, InterruptedException {
        File file = new File(fileurl);
        if(!file.exists()){
            boolean newFile = file.createNewFile();
            if(!newFile){
                log.info("创建文件失败");
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(fileurl);
        try {
            HttpClient client = HttpClient.newBuilder().build();
            AudioRequest audioRequest = new AudioRequest();
            AudioRequest.Audio audio = new AudioRequest.Audio();
            audio.setEncoding("mp3");
            audio.setVoice_type("qiniu_zh_female_wwxkjx");
            audio.setSpeed_ratio(1L);
            AudioRequest.Request request1 = new AudioRequest.Request();
            request1.setText(prompt);
            audioRequest.setAudio(audio);
            audioRequest.setRequest(request1);
            String body = JSON.toJSONString(audioRequest);
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", "application/json")
                    .header("Authorization", key)
                    .POST(HttpRequest.BodyPublishers.ofString(body))
                    .build();
            HttpResponse<String> send = client.send(request, HttpResponse.BodyHandlers.ofString());
            String responsebody = send.body();
            AudioResponse audioResponse = JSONObject.parseObject(responsebody, AudioResponse.class);
            byte[] decode = Base64.getDecoder().decode(audioResponse.getData());
            fileOutputStream.write(decode);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "文字转音频失败");
        } finally {
            fileOutputStream.close();
        }

    }
}
